﻿using System.Reflection;
using BlogSystem.Data.Entity;
using Microsoft.EntityFrameworkCore;

namespace BlogSystem.Common.Config;


public partial class DataBaseContext : DbContext
{
    protected DataBaseContext()
    {
    }

    public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options)
    {
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    }
    
    //自定义配置  构建数据库时候会被调用
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 获取了 ModelBuild 中的 Entity() 的方法
        var entityMethod = typeof(ModelBuilder).GetMethod("Entity", new Type[] { });
        //1、 获取当前程序的所以类型  2、筛选出所有实现IEntity的接口+是class+非抽象类 3、转化为list列表
        var entityTypes = Assembly.GetExecutingAssembly().GetTypes()
            .Where(s => typeof(IEntity).IsAssignableFrom(s) && s.IsClass && !s.IsAbstract)
            .Select(s => s).ToList();
        foreach (var type in entityTypes)
        {   // 将实体类型注册到模型中
            entityMethod.MakeGenericMethod(type).Invoke(modelBuilder, new object[] { });
        }
        base.OnModelCreating(modelBuilder);
    }    

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);


}